<?php

defined('SYSPATH') or die('No direct script access.');

class Stok_Model extends Model {

    public function insert_stok($data) {	
        $query = $this->db->insert('stok', $data);
        return $query->insert_id();
    }

    public function get_stok($id_stok) {
        return $this->db->from('stok')->where('ID_stok', $id_stok)->get()->current();
    }

    public function get_all_stok() {
        return $this->db->from('stok')->orderby('ID_stok')->get();
    }

    public function update_stok($id_stok, $data) {
        $this->db->where('ID_stok', $id_stok);
        $this->db->update('stok', $data);
    }

	public function increase_stok($nama, $quantity, $tanggal,$harga_beli) {					
		$query = $this->db->query('SELECT * FROM stok WHERE nama = ?',array($nama));		
		$jumlahbaru = $query->current()->jumlah + intval($quantity);				
		$this->db->query("UPDATE stok SET jumlah=? WHERE nama = ?",array($jumlahbaru,$nama));		
		$belanjastok_model = new Belanjastok_Model;
		$belanjastok_model->insert_belanjastok($query->current()->ID_stok,$tanggal,$harga_beli,$quantity);
	}
	
	//decrease stok dari produksi menu
	public function decrease_stok($nama,$quantity) {
		$query = $this->db->query('SELECT * FROM stok WHERE nama = ?',array($nama));		
		$jumlahbaru = $query->current()->jumlah - intval($quantity);
		$this->db->query("UPDATE stok SET jumlah=? WHERE nama = ?",array($jumlahbaru,$nama));		
	}
	
	public function check_already_exist_stock($nama) {
		$res = $this->db->from('stok')->get();
		foreach($res as $stok) {
			if($stok->nama == $nama) {
				return true;
			}
		}
		return false;
	}	
}